package cn.tedu.controller;

import cn.tedu.pojo.Book;
import cn.tedu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    /**
     * 查询所有书籍
     *
     * @param model model
     * @return String
     */
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Book> list = bookService.findAllBooks();
        model.addAttribute("list", list);
        return "allBook";
    }

    /**
     * 前往添加书籍页面
     *
     * @return String
     */
    @RequestMapping("/toAddBook")
    public String toAddBook() {
        return "addBook";
    }

    /**
     * 添加书籍
     *
     * @param book 实体类
     * @return String
     */
    @RequestMapping("/addBook")
    public String addBook(Book book) {
        int num = bookService.addBook(book);
        return "redirect:/book/allBook";
    }

    /**
     * 前往更新页面
     *
     * @param id 书籍id
     * @return String
     */
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id, Model model) {
        Book book = bookService.selectBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    /**
     * 更新书籍
     *
     * @param book book
     * @return String
     */
    @RequestMapping("/updateBook")
    public String updateBook(Book book) {
        int num = bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/del/{bookId}")
    public String deleteBookById(@PathVariable("bookId") int id) {
        int num = bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
}
